import { FastifyInstance, FastifyError, FastifyRequest, FastifyReply } from 'fastify';

export default async function errorHandler(fastify: FastifyInstance) {
  fastify.setErrorHandler(async (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => {
    // 记录错误
    fastify.log.error(error);

    // 根据错误类型返回不同的响应
    if (error.validation) {
      return reply.status(400).send({
        success: false,
        message: '请求参数验证失败',
        errors: error.validation,
      });
    }

    // 根据环境返回不同的错误信息
    const isDevelopment = process.env.NODE_ENV === 'development';

    if (error.statusCode) {
      return reply.status(error.statusCode).send({
        success: false,
        message: error.message,
        ...(isDevelopment && { stack: error.stack }),
      });
    }

    // 默认服务器错误
    return reply.status(500).send({
      success: false,
      message: isDevelopment ? error.message : '服务器内部错误',
      ...(isDevelopment && { stack: error.stack }),
    });
  });
}